package com.aboo.frame;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@MapperScan(basePackages = { "com.aboo.trade.**.mapper" }, sqlSessionTemplateRef = "tradeSqlSessionTemplate")
public class DbTradeMybatisConfig {

	@Bean(name = "tradeSqlSessionFactory")
	public SqlSessionFactory tradeSqlSessionFactory(@Qualifier("tradeDataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// 添加XML目录
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		try {
			bean.setMapperLocations(resolver.getResources("classpath*:mybatis/trade/**/*Mapper.xml"));
			return bean.getObject();
		} catch (Exception e) {
			log.error("数据库配置文件发生错误！", e);
			throw new RuntimeException(e);
		}
	}

	@Bean(name = "tradeSqlSessionTemplate")
	public SqlSessionTemplate tradeSqlSessionTemplate(
			@Qualifier("tradeSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		// 使用上面配置的Factory
		SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
		return template;
	}

}
